<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>构造器与原型模式Demo2</title>
  </head>
  <body>
    <div class="container container1">
      <ul class="tabHeader">
        <li class="tabItem activeTabItem">Tab</li>
        <li class="tabItem">Tab</li>
        <li class="tabItem">Tab</li>
        <li class="tabItem">Tab</li>
        <li class="tabItem">Tab</li>
      </ul>
    </div>
    <div class="container container2">
      <ul class="tabHeader">
        <li class="tabItem">Tab</li>
        <li class="tabItem">Tab</li>
        <li class="tabItem">Tab</li>
        <li class="tabItem">Tab</li>
        <li class="tabItem">Tab</li>
      </ul>
    </div>
    <script>
      class container {
        constructor(selector, eventType) {
          this.container = document.querySelector(selector);
          this.tabs = this.container.querySelectorAll(".tabHeader .tabItem");
          this.bindEvents(eventType);
        }

        // 使用箭头函数定义的属性/方法会直接挂载在对象本体上
        bindEvents = (eventType) => {
          for (let i = 0; i < this.tabs.length; i++) {
            this.tabs[i].addEventListener(eventType, () => {
              for (let n = 0; n < this.tabs.length; n++) {
                this.tabs[n].classList.remove("activeTabItem");
              }
              this.tabs[i].classList.add("activeTabItem");
            });
          }
        };

        // 使用直接定义的函数会挂载在函数的原型上
        // bindEvents(eventType) {
        //     for (let i = 0; i < this.tabs.length; i++) {
        //     this.tabs[i].addEventListener(eventType, () => {
        //       for (let n = 0; n < this.tabs.length; n++) {
        //         this.tabs[n].classList.remove("activeTabItem");
        //       }
        //       this.tabs[i].classList.add("activeTabItem");
        //     });
        //   }
        // }
      }

      console.log(new container(".container1", "click"));
      new container(".container2", "mouseover");
    </script>
    <style>
      .container {
        width: 70%;
        height: 400px;
        border: 1px solid black;
      }

      .tabHeader {
        display: flex;
        padding: 0;
        margin: 0;
      }
      .tabHeader .tabItem {
        flex: 1;
        list-style: none;
        text-align: center;
        background-color: #ddd;
      }

      .tabHeader .tabItem.activeTabItem {
        background-color: #ff7f50;
      }
    </style>
  </body>
</html>
